<template>
    <div class="header">
        <div class="header-container">
            <!-- 增加 v-if 防止 menuList 为空时报错 -->
            <el-menu v-if="menuList.length" :default-active="activeIndex" class="el-menu-demo" mode="horizontal"
                background-color="#333" text-color="#fff" active-text-color="#ffcc00" router
                :default-openeds="openMenuIds">
                <!-- 动态菜单 -->
                <template v-for="menu in menuList" :key="menu.id">
                    <!-- 无子菜单 -->
                    <el-menu-item v-if="!menu.children || !menu.children.length" :index="menu.url">
                        <router-link :to="menu.url">{{ menu.name }}</router-link>
                    </el-menu-item>
                    <!-- 有子菜单 -->
                    <el-sub-menu v-else :index="String(menu.id)">
                        <template #title>
                            <router-link :to="menu.url" class="menu-title-link">{{ menu.name }}</router-link>
                        </template>
                        <el-menu-item v-for="child in menu.children" :key="child.id" :index="child.url">
                            {{ child.name }}
                        </el-menu-item>
                    </el-sub-menu>
                </template>

                <!-- 搜索框 -->
                <el-menu-item index="/search" style="margin-left: 300px;">
                    <el-input placeholder="搜索课程/资源..." v-model="searchQuery" @keyup.enter="doSearch" />
                </el-menu-item>

                <!-- 用户中心 -->
                <el-menu-item index="20" popper-class="user-menu" v-if="userStore.isLoggedIn">
                    <template #title>
                        <div class="user-info">
                            <img :src="avatarUrl" alt="User Avatar" class="user-avatar" />
                            <span class="user-name">{{ userStore.userInfo?.username }}</span>
                            <span class="welcome-message">欢迎回来</span>
                        </div>
                    </template>
                </el-menu-item>

                <!-- 登录按钮 -->
                <el-menu-item v-else index="/login">
                    <router-link to="/auth/login">登录</router-link>
                </el-menu-item>
            </el-menu>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { user } from '@/stores/user.js'
import defaultAvatar from '@/assets/images/user/default.png'
import { getAvatar } from '@/api/avatar'
import axios from 'axios'

const avatarUrl = ref(defaultAvatar)
const userStore = user()
const router = useRouter()
const route = useRoute()
const activeIndex = ref(route.path)
const menuList = ref([])
const searchQuery = ref('')

const doSearch = () => {
    if (searchQuery.value.trim()) {
        router.push({ path: '/search', query: { q: searchQuery.value } })
    }
}

// 计算需要展开的菜单 ID 列表（关键修复）
const openMenuIds = computed(() => {
    return (menuList.value || [])
        .filter(menu =>
            Array.isArray(menu.children) &&
            menu.children.some(child => child?.url === route.path)
        )
        .map(menu => String(menu.id))
})

// 监听路由变化，更新激活菜单（设置 immediate 避免初始为空）
watch(
    () => route.path,
    (newPath) => {
        activeIndex.value = newPath
    },
    { immediate: true }
)

onMounted(async () => {
    try {
        // 获取头像
        if (userStore.userInfo?.avatar) {
            const res = await getAvatar(userStore.userInfo.avatar)
            avatarUrl.value = URL.createObjectURL(res)
        }

        // 获取菜单
        console.debug('获取菜单')
        const response = await axios.get(process.env.VUE_APP_URL + '/menu/get', {
            params: {
                roleId: userStore.userInfo?.roleId,
                type: 2,
                pageId: 1
            }
        })

        if (response.data.code === 100) {
            menuList.value = response.data.data || []
        }
    } catch (err) {
        console.error('获取菜单或头像失败', err)
        avatarUrl.value = defaultAvatar
        // 即使出错也更新activeIndex
        updateActiveIndex()
    }
})
</script>

<style lang="scss" scoped>
.header {
    background-color: #333;
    width: 100%;

    .header-container {
        max-width: 1400px;
        margin: 0 auto;
        padding: 0 20px;

        .el-menu {
            display: flex;
            justify-content: center;
            gap: 10px;
            border: none;

            :deep(a) {
                text-decoration: none;
                color: inherit;

                &:hover,
                &:visited,
                &:active {
                    color: inherit;
                }
            }

            &-item,
            .el-sub-menu__title {
                height: 60px;
                line-height: 60px;
                font-size: 15px;
                font-weight: 500;
                padding: 0 15px;
                transition: all 0.3s;
                text-align: center;
                letter-spacing: 0.5px;

                &:hover {
                    background-color: rgba(255, 255, 255, 0.1) !important;
                    color: #ffcc00;
                }

                &.is-active {
                    font-weight: 600;
                    background-color: rgba(255, 255, 255, 0.15) !important;

                    a {
                        color: #ffcc00 !important;
                    }
                }
            }
        }
    }

    :deep(.el-sub-menu__title) {
        border: none;
        text-align: center;
    }

    :deep(.el-menu--horizontal) {
        border: none;
        justify-content: center;

        .el-menu--popup {
            min-width: 150px;

            .el-menu-item {
                font-size: 14px;
                height: 45px;
                line-height: 45px;
                padding: 0 20px;

                &:hover {
                    background-color: rgba(255, 255, 255, 0.1);
                    color: #ffcc00;
                }

                &.is-active {
                    background-color: rgba(255, 255, 255, 0.15);
                    color: #ffcc00;
                }
            }
        }
    }

    .menu-title-link {
        color: inherit;
        text-decoration: none;
        display: block;
        width: 100%;
        height: 100%;

        &:hover,
        &:visited,
        &:active {
            color: inherit;
        }
    }

    .user-info {
        display: flex;
        align-items: center;
        padding: 0 10px;

        .user-avatar {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .user-name {
            color: #fff;
            font-size: 14px;
            margin-right: 8px;
        }

        .welcome-message {
            color: #ffcc00;
            font-size: 14px;
        }
    }

    :deep(.user-menu) {
        min-width: 150px;
    }
}
</style>